package pwx2gpx;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;


import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;



import java.util.*;
import java.text.*;

import java.io.File;


import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;


public class converter {
	
	public static void main(String[] args) {
  //               System.out.println(a);
                JFileChooser fileopen = new JFileChooser();
                fileopen.removeChoosableFileFilter(fileopen.getFileFilter());
                FileFilter filter = new FileNameExtensionFilter("pwx files", "pwx");
                fileopen.addChoosableFileFilter(filter);
                fileopen.setMultiSelectionEnabled(true);
                int ret = fileopen.showDialog(null, "Open file");

                
                if (ret == JFileChooser.APPROVE_OPTION) {
                	File[] ff=fileopen.getSelectedFiles();
                	for(File f:ff ) {convert(f.getPath());}
                
              
            
        }		
		
	}

	public static void convert(String file) {
		System.out.println(file);
	    try {
	    	 
	        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss"); 
	        Date timeGPX=new Date(); 
	        Date timeNew=new Date(); 

	        File fXmlFile = new File(file);
	    	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	    	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	    	Document doc = dBuilder.parse(fXmlFile);
	       	doc.getDocumentElement().normalize();
	     
	    	Node name= doc.getElementsByTagName("name").item(0);
	    	Node model= doc.getElementsByTagName("model").item(0);
	    	Node time= doc.getElementsByTagName("time").item(0);

	    	
			DocumentBuilderFactory docFactoryGPX = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilderGPX = docFactoryGPX.newDocumentBuilder();
			
	    	if( (name!=null) && (time!=null)){
	    		
	            try {
	            	timeGPX = ft.parse(time.getTextContent());
	            	}         catch (ParseException e) {
	                    ;
	                }
		    	String stName= new String(name.getTextContent()+"_"+time.getTextContent()+"Z");
		    	
				Document docGPX = docBuilderGPX.newDocument();	    	
				Element rootElementGPX = docGPX.createElement("gpx");
				rootElementGPX.setAttribute("xmlns", "http://www.topografix.com/GPX/1/1 ");
				rootElementGPX.setAttribute("xmlns:creator", "Galin_Dimitrov_"+name.getTextContent());
				rootElementGPX.setAttribute("xmlns:version", "1.1");
				rootElementGPX.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
				rootElementGPX.setAttribute("xmlns:schemaLocation", "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd");
				docGPX.appendChild(rootElementGPX);

				Element metaElementGPX = docGPX.createElement("metadata");
				rootElementGPX.appendChild(metaElementGPX);
				
				Element elName=docGPX.createElement("name");
				elName.appendChild(docGPX.createTextNode(stName));
				metaElementGPX.appendChild(elName);
				
				elName=docGPX.createElement("time");
				elName.appendChild(docGPX.createTextNode(time.getTextContent()+"Z"));
				metaElementGPX.appendChild(elName);
			
				Element trkElementGPX = docGPX.createElement("trk");
				rootElementGPX.appendChild(trkElementGPX);

				elName=docGPX.createElement("name");
				elName.appendChild(docGPX.createTextNode(stName));
				trkElementGPX.appendChild(elName);
				
				Element elTrkseq=docGPX.createElement("trkseg");
				trkElementGPX.appendChild(elTrkseq);

				Element elPntq;
				Element elEle;
				Element elTime;
				
				Element eElement;
				
		    	NodeList nList = doc.getElementsByTagName("sample");
		     		     
		    	for (int temp = 0; temp < nList.getLength(); temp++) {
		     
		    		Node nNode = nList.item(temp);
		     		     
		    		if (nNode.getNodeType() == Node.ELEMENT_NODE) {

		    			eElement = (Element) nNode;
		    			
		    			if ( eElement.getElementsByTagName("lat").item(0) != null ) {
			    			
							elPntq=docGPX.createElement("trkpt");
							elEle=docGPX.createElement("ele");
							elTime=docGPX.createElement("time");	
							try{
								timeNew.setTime(timeGPX.getTime()+(long) (1000*Double.valueOf(eElement.getElementsByTagName("timeoffset").item(0).getTextContent())));
							}
							catch (Exception e) {    e.printStackTrace()     ; }
							elPntq.setAttribute("lat", eElement.getElementsByTagName("lat").item(0).getTextContent()+"00");
							elPntq.setAttribute("lon", eElement.getElementsByTagName("lon").item(0).getTextContent()+"00");
							if ( eElement.getElementsByTagName("alt").item(0) != null )
    							elEle.appendChild(docGPX.createTextNode(eElement.getElementsByTagName("alt").item(0).getTextContent()));
							else 
								elEle.appendChild(docGPX.createTextNode("0.00"));
							elTime.appendChild(docGPX.createTextNode(ft.format(timeNew)));
							elPntq.appendChild(elEle);
							elPntq.appendChild(elTime);
							
							
							elTrkseq.appendChild(elPntq);
		     
		    			};
		    		}
		    	}
		    	
		    	
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(docGPX);
				StreamResult result = new StreamResult(new File(file.replace(".pwx", ".gpx")));
		
		 
				transformer.transform(source, result);
		 
				System.out.println("File saved!");
		    	
	    		}
	        } catch (Exception e) {
	    	e.printStackTrace();
	        }	      
		
	}

}
